package com.alipay.app.groupmeal.standard.ui.c.abcp;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alipay.app.groupmeal.standard.R;
import com.alipay.app.groupmeal.standard.base.BaseMVCActivity;

import com.alipay.app.groupmeal.standard.bean.AliPayResVo;
import com.alipay.app.groupmeal.standard.http.bean.resp.Result;
import com.alipay.app.groupmeal.standard.offline.bean.OrderBean;
import com.alipay.app.groupmeal.standard.offline.manager.OrderDataManager;
import com.alipay.app.groupmeal.standard.ui.b.function.HexiaoPre;
import com.alipay.app.groupmeal.standard.ui.c.pre.CHexiaoCardMainPre;

import com.alipay.app.groupmeal.standard.ui.b.util.NFCManager;
import com.alipay.app.groupmeal.standard.ui.b.util.WIth;
import com.alipay.app.groupmeal.standard.util.ByteUtil;
import com.alipay.app.groupmeal.standard.util.USBTransferUtil;
import com.alipay.iot.bpaas.api.service.BPaaSCallback;
import com.alipay.iot.bpaas.api.service.BPaaSResponse;
import com.alipay.iot.bpaas.api.utils.StringUtil;
import com.alipay.iot.sdk.APIManager;
import com.alipay.iot.sdk.payment.PaymentAPI;
import com.alipay.sdk.abcphaima.AbcpHM;
import com.alipay.sdk.abcphaima.AbcpQuotaAuthPage;
import com.alipay.sdk.abcphaima.bean.PageResultData;
import com.yzy.voice.VoicePlay;

import java.util.Date;
import java.util.LinkedList;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Flowable;
import io.reactivex.rxjava3.disposables.Disposable;
import io.reactivex.rxjava3.functions.Action;
import io.reactivex.rxjava3.functions.Consumer;
import io.reactivex.rxjava3.internal.observers.BlockingBaseObserver;

public class CHexiaoAuthActivity extends BaseMVCActivity implements NFCManager.OnReceiveNfcTagCallback {

    public static CHexiaoAuthActivity quotaAuthActivity = null;

    private HexiaoPre hexiaoPre;

    private CHexiaoCardMainPre scanQrMainPre;

    // NFC读卡
    private NFCManager mNFCManager;

    Disposable mdDisposable;

    private final int closeSec = 4;

    private TextView tv_close_time;

    private LinearLayout ll_cancel;

    private ConstraintLayout loadingCon;

    private LinearLayout payResLinear;

    private TextView payResMsgTv;

    private TextView amountPrice;
    private TextView accountPrice;
    private TextView youhuiPrice;


    public static void startActAbcp(Context activity) {
        Intent intent = new Intent(activity, CHexiaoAuthActivity.class);
        activity.startActivity(intent);
    }

    @Override
    public boolean onKeyEventBack(KeyEvent event) {
        finish();
        return super.onKeyEventBack(event);
    }


    @Override
    protected int getLayoutId() {
        return R.layout.activity_transparent;
    }

    @Override
    protected void initView() {
        quotaAuthActivity = this;
        mNFCManager = new NFCManager(this);
    }


    @Override
    protected void initData() {

    }

    @Override
    protected void dissmissPresnetation() {
        if (hexiaoPre != null) {
            hexiaoPre.dismiss();
        }

    }

    @Override
    public void initPresentation() {
        super.initPresentation();
        if (mDisplay != null) {
            hexiaoPre = new HexiaoPre(this, mDisplay);
            registerPresentation(hexiaoPre);
            showPresentation(hexiaoPre);
            hexiaoPre.shows();
        }
        //abcp刷脸服务
        abcp();
    }

    private void abcp() {
        AbcpQuotaAuthPage.showPage(new AbcpHM.AbcpScanFaceCallback() {
            @Override
            public void onSuccess(boolean isFace, String authCode, String barCode, String tradeNo, String sessionId, String alipayUid) {
                PaymentAPI api = APIManager.getInstance().getPaymentAPI();
                String terminal_params = api.signWithDelegated(authCode);
                OrderBean orderBean = new OrderBean();
                orderBean.setSuccess(false);//在线模式，订单为未知状态，则不是成功状态
                orderBean.setHavePost(true);//在线模式，订单服务器上操作，则表示为上传订单
                orderBean.setAuthCode(authCode);
                orderBean.setTradeNo(tradeNo);
                orderBean.setCreateTime(new Date());
                OrderDataManager.getInstance().insert(orderBean);

                new WIth(quotaAuthActivity).facePayV2("",
                        tradeNo,
                        sessionId,
                        authCode,
                        alipayUid, terminal_params,
                        new LinkedList<>(),
                        new BlockingBaseObserver<Result<AliPayResVo>>() {
                            @Override
                            public void onNext(@NonNull Result<AliPayResVo> aliPayResVoResult) {
                                try {
                                    AliPayResVo aliPayResVo = aliPayResVoResult.getResult();
                                    System.out.println("正常：" + aliPayResVo.toString());
                                    toResult(isFace ? 0 : 1, authCode, "0",
                                            tradeNo, sessionId, "", aliPayResVo.isSuccess(),
                                            aliPayResVo.getIsFailType(), aliPayResVo.getFailCode(), aliPayResVo.getMsg(),
                                            aliPayResVoResult.getResult());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onError(@NonNull Throwable e) {

                            }
                        });


//                new WIth(quotaAuthActivity).hexiao1(
//                        isFace ? "" : authCode,
//                        isFace ? authCode : "",
//                        alipayUid,
//                        tradeNo,
//                        sessionId, terminal_params,
//                        new BlockingBaseObserver<Result<AliPayResVo>>() {
//                            @Override
//                            public void onNext(@NonNull Result<AliPayResVo> aliPayResVoResult) {
//                                AliPayResVo aliPayResVo = aliPayResVoResult.getResult();
//
//                                String username = "";
//                                try {
//                                    username = aliPayResVo.getFk().getName();
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//
//                                toResult(isFace ? 0 : 1, authCode,
//                                        tradeNo, sessionId, "", aliPayResVo.isSuccess(),
//                                        0, "1", aliPayResVo.getMsg(),
//                                        aliPayResVo.getAmountPrice(), aliPayResVo.getAccountPrice(),
//                                        aliPayResVo.getYouhuiPrice(), username);
//                                if (aliPayResVo.isSuccess()) {
//                                    //支付成功订单，需要更改标志，并存入数据库
//                                    orderBean.setCardno(aliPayResVo.getFk().getCardno());
//                                    orderBean.setUserName(aliPayResVo.getFk().getName());
//                                    orderBean.setAmount(aliPayResVo.getAmountPrice());
//                                    orderBean.setSuccess(true);
//                                    OrderDataManager.getInstance().update(orderBean);
//                                }
//                            }
//
//                            @Override
//                            public void onError(@NonNull Throwable e) {
//
//                            }
//                        });

            }

            @Override
            public void onFail(String code, String msg) {
                System.out.println("code:" + code + "    msg:" + msg);
                if ("1003".equals(code)) {
                    close();
                }
            }

            @Override
            public void onEvent(String sessionId) {

            }
        });
    }

    private void close() {
        AbcpQuotaAuthPage.close(new AbcpHM.AbcpLoadingCallback() {
            @Override
            public void onSuccess(String tradeNo, String sessionId, String alipayUid) {
                finish();
                System.out.println("触发");
            }

            @Override
            public void onFail(String code, String msg) {

            }

            @Override
            public void onEvent(String sessionId) {

            }
        });
    }


    @Override
    protected void onDestroy() {
        if (mdDisposable != null && !mdDisposable.isDisposed()) {
            mdDisposable.dispose();
            mdDisposable = null;
        }
        super.onDestroy();
        quotaAuthActivity = null;
    }
    private void toResult(int type, final String authCode, String amount,
                          final String tradeNo, final String sessionId, String buyerLogonId,
                          boolean isSuccess, int isFailType, String failCode, String msg, AliPayResVo aliPayResVo) {
        PageResultData pageResultData = new PageResultData();
        pageResultData.success = isSuccess;
        if (isSuccess) {
            pageResultData.buyerLogonId = buyerLogonId;
            if (USBTransferUtil.isOpen) {
                byte[] to_send = ByteUtil.hexStringToByte("A00106A7");
                int rel = USBTransferUtil.driver.WriteData(to_send, to_send.length);
                if (rel < 0) {
                    USBTransferUtil.isOpen = false;
                    USBTransferUtil.driver.CloseDevice();
                }
            }
        } else {
            pageResultData.failCode = failCode;
            pageResultData.message = msg;
        }
        pageResultData.totalAmount = aliPayResVo.getAmount();
        pageResultData.paidAmount = aliPayResVo.getAmount();
        pageResultData.authCode = authCode;
        pageResultData.tradeNo = tradeNo;
        pageResultData.sessionId = sessionId;
        pageResultData.type = type;
        pageResultData.outerExtends = aliPayResVo.getOuterExtends();
        CPayResultAbcpActivity.startAct(CHexiaoAuthActivity.this, pageResultData);
    }

//    private void toResult(int type, final String authCode,
//                          final String tradeNo, final String sessionId, String buyerLogonId,
//                          boolean isSuccess, int isFailType, String failCode, String msg, String amountPrice,
//                          String accountPrice,
//
//                          String youhuiPrice,
//                          String username) {
//
//        String operateType = "";
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("success", isSuccess);
//        jsonObject.put("tradeNo", tradeNo);
//        jsonObject.put("sessionId", sessionId);
//        jsonObject.put("resultTimeOut", 3);
//        if (type == 0) {
//            jsonObject.put("ftoken", authCode);
//            operateType = "showScanFaceOfflinePayResult";
//        } else if (type == 1) {
//            jsonObject.put("scanCode", authCode);
//            operateType = "showScanCodeOfflinePayResult";
//        }
//
//        jsonObject.put("advancedConfig", createAdvancedConfig(msg, isSuccess, amountPrice, accountPrice, youhuiPrice, username).toJSONString());
//        if ("操作成功".equals(msg) ||
//                "支付成功".equals(msg)) {
//            VoicePlay.with(this).success();
//        } else if ("你已消费".equals(msg)) {
//            VoicePlay.with(this).nyxf();
//        }
//
//        AbcpHM.startCanteenBPaaSService("payResult", operateType,
//                jsonObject, new BPaaSCallback() {
//                    @Override
//                    public void onResponse(BPaaSResponse bPaaSResponse) {
//
//                    }
//
//                    @Override
//                    public void onEvent(String s, String s1, Bundle bundle) {
//
//                    }
//                });
//    }

    private static JSONObject createAdvancedConfig(String msg, boolean success, String amountPrice,
                                                   String accountPrice,

                                                   String youhuiPrice, String username) {


        JSONObject advancedConfig = new JSONObject();
        advancedConfig.put("version", "2.0");// 表示启用新版本结果页，必须
        JSONObject OuterSummary = new JSONObject();
        OuterSummary.put("enablePaymentVoice", true);// 语音播报开关，非必须
        OuterSummary.put("title", msg);// 结果页标题，必须
        advancedConfig.put("OuterSummary", OuterSummary);
        if (success) {
            JSONArray extend = new JSONArray();
            JSONObject object = new JSONObject();
            JSONObject detail = new JSONObject();
            object.put("title", "");
            object.put("color", "#333333");
            detail.put("name", "姓名");
            detail.put("value", username.trim());
            object.put("detail", detail);
            extend.add(object);

            object = new JSONObject();
            detail = new JSONObject();
            object.put("title", "");
            object.put("color", "#333333");
            detail.put("name", "订单金额");
            detail.put("value", amountPrice);
            object.put("detail", detail);
            extend.add(object);

            object = new JSONObject();
            detail = new JSONObject();
            object.put("title", "");
            object.put("color", "#333333");
            detail.put("name", "个人支付");
            detail.put("value", accountPrice);
            object.put("detail", detail);
            extend.add(object);

            object = new JSONObject();
            detail = new JSONObject();
            object.put("title", "");
            object.put("color", "#333333");
            detail.put("name", "优惠金额");
            detail.put("value", youhuiPrice);
            object.put("detail", detail);
            extend.add(object);
            advancedConfig.put("OuterExtends", extend);
        }
        return advancedConfig;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        mNFCManager.receiveTag(intent);

    }

    @Override
    public void onReceiveNfcTag(String tag) {
        //正在支付页面，开始刷卡支付
        if (mMainDisplay != null) {
            if (scanQrMainPre != null && scanQrMainPre.isShowing()) {
                return;
            }
            scanQrMainPre = new CHexiaoCardMainPre(CHexiaoAuthActivity.this, mMainDisplay);
            scanQrMainPre.setOwnerActivity(this);
            tv_close_time = scanQrMainPre.getTv_close_time();
            ll_cancel = scanQrMainPre.getLl_cancel();
            loadingCon = scanQrMainPre.getLoadingCon();
            payResLinear = scanQrMainPre.getPayResLinear();
            payResMsgTv = scanQrMainPre.getPayResMsgTv();
            amountPrice = scanQrMainPre.getAmountPrice();
            accountPrice = scanQrMainPre.getAccountPrice();
            youhuiPrice = scanQrMainPre.getYouhuiPrice();


            scanQrMainPre.setBackListener((hexiaoOrderModel) -> {
                tv_close_time.setVisibility(View.VISIBLE);
                payResLinear.setVisibility(View.VISIBLE);
                ll_cancel.setVisibility(View.VISIBLE);
                loadingCon.setVisibility(View.GONE);
                if (hexiaoOrderModel != null || !StringUtil.isEmpty(hexiaoOrderModel.getMsg())) {
                    payResMsgTv.setText(hexiaoOrderModel.getMsg());
                    try {
                        if ("操作成功".equals(hexiaoOrderModel.getMsg()) ||
                                "支付成功".equals(hexiaoOrderModel.getMsg())) {
                            VoicePlay.with(this).success();


                            if (USBTransferUtil.isOpen) {
                                byte[] to_send = ByteUtil.hexStringToByte("A00106A7");
                                int rel = USBTransferUtil.driver.WriteData(to_send, to_send.length);
                                if (rel < 0) {
                                    USBTransferUtil.isOpen = false;
                                    USBTransferUtil.driver.CloseDevice();
                                }
                            }
                        } else if ("当前用户在当前餐次已消费".equals(hexiaoOrderModel.getMsg())) {
                            VoicePlay.with(this).nyxf();
                        }
                        amountPrice.setText("总金额：" + hexiaoOrderModel.getAmountPrice());
                        accountPrice.setText("个人支付金额：" + hexiaoOrderModel.getAccountPrice());
                        youhuiPrice.setText("优惠金额：" + hexiaoOrderModel.getYouhuiPrice());
                    } catch (Exception e) {

                    }

                } else {
                    payResMsgTv.setText("网络错误");
                }
                initTime();
            });

            ll_cancel.setOnClickListener(view -> {
                scanQrMainPre.dismiss();
                mdDisposable.dispose();
            });

        }
        payResLinear.setVisibility(View.GONE);
        loadingCon.setVisibility(View.VISIBLE);
        scanQrMainPre.cardHexiao(tag);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mNFCManager.dispatch();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mNFCManager.cancelDispatch();
    }

    @Override
    public void onBusiness() {
        super.onBusiness();

    }

    public void initTime() {
        mdDisposable = Flowable.intervalRange(0, closeSec, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnNext(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {
                        String btnText = (closeSec - aLong) + "秒";
                        tv_close_time.setText(btnText);
                    }
                })
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        scanQrMainPre.dismiss();
                    }
                })
                .subscribe();
    }


}
